package com.suncnpap.base.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.app.util.common.FileUtil;
import com.app.util.common.HandlerResult;
import com.app.util.common.HandlerResultMobile;
import com.app.util.common.PathUtil;
import com.app.util.common.ResponseUtil;
import com.app.util.common.SysConfig;
import com.app.util.common.UuidUtil;

/**
 * 上传文件
 * 
 */

@Controller
@RequestMapping("/uploadFile")
public class UploadPicAPIController extends BaseController {

	@RequestMapping(value = "/addFile")
	public void SaveDoc(HttpServletRequest request, HttpServletResponse response) throws Exception {

		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

		HandlerResult result = this.checkToken(multiRequest);

		if (result.getCode()==0) {//
			
			String strModule = multiRequest.getParameter("strModule");//文件类型
			
			String F_Name = UuidUtil.get32UUID();// 最终保存的文件名称
			String F_Path = "/upload/"+strModule+"/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+"/";
			
			
			String strPath = F_Path;// 文件路径

			// 使用getMultiFileMap获取objFile对象值在
			MultiValueMap<String, MultipartFile> fileMap = multiRequest.getMultiFileMap();
			/** 开始fileMap对象的foreach循环 **/
			for (Entry<String, List<MultipartFile>> fileList : fileMap.entrySet()) {

				for (int i = 0; i < fileList.getValue().size(); i++) {
					
					MultipartFile file =  fileList.getValue().get(i);
					
					
					F_Name = F_Name +"."+ FileUtil.getFileExt(file.getOriginalFilename());
					String strFolder = PathUtil.getClasspath() + strPath;
					String strFileName = F_Name;
					File f = new File(strFolder);
					if (!f.exists()) {
						f.mkdirs();
					} else {
						if (!strFileName.equals("")) {
							File strFile = new File(strFolder + strFileName);
							if (strFile.exists())
								strFile.delete();
						}
					}
					File fileForld = new File(PathUtil.getClasspath() + strPath + strFileName);
					file.transferTo(fileForld);
					
					result.put("strUrl", PathUtil.PathAddress() + F_Path + F_Name);
				}
			}

			
			
			
		}
		ResponseUtil.writeJson(result, response);
	}
}
